<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column align="center" label="操作" width="240">
                <template slot-scope="{row}">
                  <el-button size="small" type="success" @click="hAssignPer(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2,3,5,8,10]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
              <el-pagination layout="prev,pager,next" />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 准备新增的弹窗 -->
      <el-dialog :title="isEdit? '编辑角色':'新增角色'" :visible.sync="showDialog" @close="hClose">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="hsubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹窗 -->
      <el-dialog :visible.sync="perShowDialog" title="权限分配">
        <assignPer :role-id="roleId" @success="perShowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, addtRoles, editRoles, delRoles } from '@/api/settings'
import assignPer from './assignPermission.vue'
export default {
  components: {
    assignPer
  },
  data() {
    return {
      perShowDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色的名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入角色的描述', trigger: 'blur' }]
      },
      showDialog: false,
      list: [],
      pageParams: {
        page: 1, // 当前页数
        pagesize: 3// 每页显示的条数
      },
      total: 0,
      isEdit: false,
      roleId: ''

    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssignPer(id) {
      this.roleId = id
      this.perShowDialog = true
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res, 'getRoles')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
        this.$message.error('请求错误')
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1// 重置后将当前页面重置为1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val // 改变请求参数的页码值
      this.loadRoles()
    },
    hsubmit() {
      this.$refs.roleForm.validate(valid => {
        if (!valid) return
        // 同一个确定用isEdit来判断
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    async  doAdd() {
      try {
        const res = await addtRoles(this.roleForm)
        console.log(res, 'addtRoles')
        this.total++// 加完了再去发服务器，否则连续加的时候页面渲染不及时数据还是上次的(total)
        // 计算出最大得到页码值并且向上取整 Math.ceil，将请求页码值转成最大页码值
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        this.pageParams.page = maxPage
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    async  hAdd() {
      try {
        this.isEdit = false
        this.showDialog = true
      } catch (error) {
        console.log(error)
      }
    },
    async  doEdit() {
      try {
        const res = await editRoles(this.roleForm)
        console.log(res, 'editRoles')
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    async  hEdit(row) {
      try {
        console.log(row, 'row')
        this.isEdit = true
        this.roleForm = { ...row }// 此处用浅拷贝是为了防止我们同步的修改我们的数据。浅拷贝绑定的是地址
        this.showDialog = true
      } catch (error) {
        console.log(error)
      }
    },
    async hDel(id) {
      this.$confirm('确认删除？').then(
        async() => {
          const res = await delRoles(id)
          if (this.list.length === 1) {
            this.pageParams.page--

            if (this.pageParams.page <= 0) {
              this.pageParams.page = 1
            }
            console.log(res, 'delRoles')
          }
          this.loadRoles()
        }
      ).catch(error => console.log(error))
    },
    hClose() {
      // 将表单回到初始的状态不一定是空喔！
      this.$refs.roleForm.resetFields()// 这个是回到初始状态与清空校验的规则
      this.roleForm = {
        name: '',
        description: ''
      }
    }

  }
}
</script>

